<template>
  <div class="maintenance-task-list-container">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.taskName" placeholder="任务名称" clearable />
        </el-form-item>
        <el-form-item label="关联设备">
          <el-select
            v-model="searchForm.deviceId"
            placeholder="请选择设备"
            filterable
            clearable
          >
            <el-option
              v-for="item in allDevices"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="searchForm.taskType" placeholder="请选择" clearable>
            <el-option label="预防性维护" value="预防性维护" />
            <el-option label="事后维护" value="事后维护" />
            <el-option label="改进性维护" value="改进性维护" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待执行" value="待执行" />
            <el-option label="执行中" value="执行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已驳回" value="已驳回" />
            <el-option label="已关闭" value="已关闭" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择" clearable>
            <el-option label="低" value="低" />
            <el-option label="中" value="中" />
            <el-option label="高" value="高" />
            <el-option label="紧急" value="紧急" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人">
          <el-select
            v-model="searchForm.assigneeId"
            placeholder="请选择处理人"
            filterable
            clearable
          >
            <el-option
              v-for="user in maintenanceUsers"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间">
          <el-date-picker
            v-model="searchForm.planTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 280px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="content-card">
      <div class="content-header">
        <el-radio-group v-model="currentView" size="small" style="margin-right: 20px;">
          <el-radio-button label="list">列表视图</el-radio-button>
          <el-radio-button label="kanban">看板视图</el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="handleAddTask">新增维护任务</el-button>
        <el-button type="danger" :disabled="selectedTasks.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 列表视图 -->
      <div v-if="currentView === 'list'" class="list-view">
        <el-table
          :data="taskList"
          v-loading="loading"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="taskId" label="任务ID" width="90" />
          <el-table-column prop="taskName" label="任务名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="deviceName" label="关联设备" width="140" show-overflow-tooltip />
          <el-table-column prop="taskType" label="任务类型" width="120" />
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
                <el-tag :type="getTagType(row.priority, 'priority')">{{ row.priority }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
                <el-tag :type="getTagType(row.status, 'status')">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assigneeName" label="处理人" width="100">
              <template #default="{ row }">
                  {{ row.assigneeName || '未分配' }}
              </template>
          </el-table-column>
          <el-table-column prop="reporter" label="报告人" width="100" />
          <el-table-column label="计划时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.planStartTime) }}<br/>至<br/>{{ formatTime(row.planEndTime) }}
            </template>
          </el-table-column>
          <el-table-column label="实际时间" width="180">
            <template #default="{ row }">
              {{ row.actualStartTime ? formatTime(row.actualStartTime) : '未开始' }}<br/>至<br/>{{ row.actualEndTime ? formatTime(row.actualEndTime) : '未完成' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleViewDetail(row)">详情</el-button>
              <el-button type="warning" link size="small" @click="handleEditTask(row)">编辑/执行</el-button>
              <el-button type="danger" link size="small" @click="handleDeleteTask(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 看板视图 -->
      <div v-if="currentView === 'kanban'" class="kanban-view">
        <DraggableKanban
          :tasks="taskList"
          @update:taskStatus="handleTaskStatusUpdate"
          @view-detail="handleViewDetail"
          @edit-task="handleEditTask"
          @delete-task="handleDeleteTask"
        />
      </div>
    </el-card>

    <!-- 新增/编辑任务弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑维护任务' : '新增维护任务'"
      width="750px"
      :before-close="handleCloseDialog"
    >
      <el-form
        :model="taskForm"
        :rules="taskFormRules"
        ref="taskFormRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="taskForm.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联设备" prop="deviceId">
              <el-select
                v-model="taskForm.deviceId"
                placeholder="请选择关联设备"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in allDevices"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="taskForm.taskType" placeholder="请选择任务类型" style="width: 100%">
                <el-option label="预防性维护" value="预防性维护" />
                <el-option label="事后维护" value="事后维护" />
                <el-option label="改进性维护" value="改进性维护" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="taskForm.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="低" value="低" />
                <el-option label="中" value="中" />
                <el-option label="高" value="高" />
                <el-option label="紧急" value="紧急" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="计划开始时间" prop="planStartTime">
                    <el-date-picker
                        v-model="taskForm.planStartTime"
                        type="datetime"
                        placeholder="选择计划开始时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="计划完成时间" prop="planEndTime">
                    <el-date-picker
                        v-model="taskForm.planEndTime"
                        type="datetime"
                        placeholder="选择计划完成时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item label="任务描述" prop="description">
          <el-input
            type="textarea"
            v-model="taskForm.description"
            :rows="3"
            placeholder="请输入任务详细描述"
          />
        </el-form-item>

        <el-form-item label="报告人" prop="reporter" v-if="!isEdit">
          <el-input v-model="taskForm.reporter" placeholder="请输入任务报告人/发起人" />
        </el-form-item>

        <!-- 管理员操作区 (仅管理员或特定角色可见) -->
        <el-divider v-if="isEdit" content-position="left">任务分配/状态</el-divider>
        <el-row :gutter="20" v-if="isEdit">
            <el-col :span="12">
                <el-form-item label="处理人" prop="assigneeId">
                    <el-select
                        v-model="taskForm.assigneeId"
                        placeholder="请选择处理人"
                        filterable
                        clearable
                        style="width: 100%;"
                    >
                        <el-option
                            v-for="user in maintenanceUsers"
                            :key="user.userId"
                            :label="user.userName"
                            :value="user.userId"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="任务状态" prop="status">
                    <el-select v-model="taskForm.status" placeholder="请选择任务状态" style="width: 100%">
                        <el-option label="待执行" value="待执行" />
                        <el-option label="执行中" value="执行中" />
                        <el-option label="已完成" value="已完成" />
                        <el-option label="已驳回" value="已驳回" />
                        <el-option label="已关闭" value="已关闭" />
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 维修人员操作区 (仅已分配并执行中的任务可见) -->
        <el-divider v-if="isEdit && (isMaintainer || isCurrentAssignee) && taskForm.status !== '待执行'" content-position="left">任务执行/报告</el-divider>
        <template v-if="isEdit && (isMaintainer || isCurrentAssignee) && taskForm.status !== '待执行'">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="实际开始时间" prop="actualStartTime">
                        <el-date-picker
                            v-model="taskForm.actualStartTime"
                            type="datetime"
                            placeholder="选择实际开始时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%"
                            :disabled="taskForm.status === '待执行' || taskForm.actualStartTime !== ''"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="实际完成时间" prop="actualEndTime">
                        <el-date-picker
                            v-model="taskForm.actualEndTime"
                            type="datetime"
                            placeholder="选择实际完成时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%"
                            :disabled="taskForm.status !== '已完成' && taskForm.status !== '已关闭'"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="维修措施" prop="maintenanceMeasures">
                <el-input
                  type="textarea"
                  v-model="taskForm.maintenanceMeasures"
                  :rows="3"
                  placeholder="请输入采取的维修措施和具体操作过程"
                  :disabled="taskForm.status === '已完成' || taskForm.status === '已关闭'"
                />
            </el-form-item>
            <el-form-item label="维修结果" prop="maintenanceResult">
                <el-input
                  type="textarea"
                  v-model="taskForm.maintenanceResult"
                  :rows="2"
                  placeholder="请输入维修后的结果和设备状态"
                  :disabled="taskForm.status === '已完成' || taskForm.status === '已关闭'"
                />
            </el-form-item>
            <el-form-item label="上传附件">
                <el-upload
                    action="#"
                    :auto-upload="false"
                    :file-list="fileList"
                    :on-change="handleFileChange"
                    :on-remove="handleFileRemove"
                    :http-request="uploadFile"
                    :limit="1"
                    :disabled="taskForm.status === '已完成' || taskForm.status === '已关闭'"
                >
                    <el-button type="primary" :disabled="taskForm.status === '已完成' || taskForm.status === '已关闭'">选择文件</el-button>
                    <template #tip>
                      <div class="el-upload__tip">支持图片、PDF文件，大小不超过5MB。<span v-if="taskForm.attachmentUrl"> (当前已上传: <el-link :href="taskForm.attachmentUrl" target="_blank">{{ taskForm.attachmentUrl.split('/').pop() }}</el-link>)</span></div>
                    </template>
                </el-upload>
            </el-form-item>
        </template>

        <!-- 管理员额外备注 (所有状态都可写) -->
        <el-divider v-if="isEdit" content-position="left">管理员备注</el-divider>
        <el-form-item label="管理员备注" prop="adminRemark" v-if="isEdit">
          <el-input
            type="textarea"
            v-model="taskForm.adminRemark"
            :rows="2"
            placeholder="管理员审核或驳回的备注"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer maintenance-footer-actions">
          <el-button @click="handleCloseDialog">取消</el-button>
          <template v-if="isEdit">
            <!-- 维修人员操作按钮 -->
            <el-button
                v-if="isCurrentAssigneeOrAdmin && taskForm.status === '待执行'"
                type="primary"
                @click="performAction('startTask')"
                :loading="formSubmitting"
            >
                开始执行
            </el-button>
            <el-button
                v-if="isCurrentAssigneeOrAdmin && taskForm.status === '执行中'"
                type="success"
                @click="performAction('submitReport')"
                :loading="formSubmitting"
            >
                提交报告
            </el-button>
            <!-- 管理员操作按钮 -->
            <el-button
                v-if="isAdmin && (taskForm.status === '已完成' || taskForm.status === '已驳回')"
                type="info"
                @click="performAction('closeTask')"
                :loading="formSubmitting"
            >
                关闭任务
            </el-button>
            <el-button
                v-if="isAdmin && (taskForm.status === '待执行' || taskForm.status === '执行中')"
                type="plain"
                @click="performAction('rejectTask')"
                :loading="formSubmitting"
            >
                驳回
            </el-button>
            <el-button type="primary" @click="handleSubmitForm" :loading="formSubmitting">
                保存修改
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="handleSubmitForm" :loading="formSubmitting">新增任务</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getTaskList,
  addTask,
  updateTask,
  deleteTask,
  getMaintenanceUsers,
  uploadAttachment
} from '@/stores/maintenance'; // 引入维护API
import { getAllDevices } from '@/stores/device'; // 引入设备API
import DraggableKanban from '@/components/DraggableKanban.vue';
import { format } from 'date-fns';

// --- 模拟当前登录用户信息 (用于权限控制) ---
const currentUser = reactive({
    id: 4, // 1:张三(维修工), 2:李四(维修工), 3:王五(点检员), 4:赵六(管理员)
    name: '赵六',
    role: '管理员' // '维修工', '点检员', '管理员'
});

const isMaintainer = computed(() => currentUser.role === '维修工');
const isAdmin = computed(() => currentUser.role === '管理员');
const isCurrentAssignee = computed(() => taskForm.assigneeId && taskForm.assigneeId === currentUser.id);
const isCurrentAssigneeOrAdmin = computed(() => isCurrentAssignee.value || isAdmin.value);

// --- 搜索表单相关 ---
const searchForm = reactive({
  taskName: '',
  deviceId: null,
  taskType: '',
  status: '',
  priority: '',
  assigneeId: null,
  reporter: '',
  planTimeRange: [],
});

const handleSearch = () => {
  pagination.page = 1;
  fetchTaskList();
};

const handleResetSearch = () => {
  searchForm.taskName = '';
  searchForm.deviceId = null;
  searchForm.taskType = '';
  searchForm.status = '';
  searchForm.priority = '';
  searchForm.assigneeId = null;
  searchForm.reporter = '';
  searchForm.planTimeRange = [];
  handleSearch();
};

// --- 视图切换 ---
const currentView = ref('list'); // 'list' 或 'kanban'

// --- 表格/看板数据相关 ---
const taskList = ref([]);
const loading = ref(false);
const selectedTasks = ref([]);

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 所有设备列表
const allDevices = ref([]);
const fetchAllDevices = async () => {
  try {
    const res = await getAllDevices();
    if (res.code === 200) {
      allDevices.value = res.data;
    } else {
      ElMessage.error(res.message || '获取设备列表失败');
    }
  } catch (error) {
    ElMessage.error('请求所有设备列表异常');
    console.error(error);
  }
};

// 所有维修人员列表
const maintenanceUsers = ref([]);
const fetchMaintenanceUsers = async () => {
  try {
    const res = await getMaintenanceUsers();
    if (res.code === 200) {
      maintenanceUsers.value = res.data;
    } else {
      ElMessage.error(res.message || '获取维修人员列表失败');
    }
  } catch (error) {
    ElMessage.error('请求维修人员列表异常');
    console.error(error);
  }
};

const fetchTaskList = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      planTimeRange: searchForm.planTimeRange && searchForm.planTimeRange.length === 2
                       ? searchForm.planTimeRange : undefined,
      page: pagination.page,
      pageSize: pagination.pageSize,
    };
    const res = await getTaskList(params);
    if (res.code === 200) {
      taskList.value = res.data.list.map(task => { // 确保 deviceName存在
        const device = allDevices.value.find(d => d.value === task.deviceId);
        return {
          ...task,
          deviceName: device ? device.label : '未知设备'
        };
      });
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.message || '获取维护任务列表失败');
    }
  } catch (error) {
    ElMessage.error('请求维护任务列表异常');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchAllDevices();
  fetchMaintenanceUsers().then(() => {
    fetchTaskList(); // 确保设备和用户加载完成后再加载任务列表
  });
});

const handleSelectionChange = (val) => {
  selectedTasks.value = val;
};

const getTagType = (value, type) => {
  if (type === 'priority') {
    switch (value) {
      case '低': return 'info';
      case '中': return '';
      case '高': return 'warning';
      case '紧急': return 'danger';
      default: return '';
    }
  } else if (type === 'status') {
    switch (value) {
      case '待执行': return 'danger';
      case '执行中': return 'warning';
      case '已完成': return 'success';
      case '已驳回': return 'info';
      case '已关闭': return ''; // 默认灰色
      default: return '';
    }
  }
  return '';
};

const formatTime = (timeStr) => {
    if (!timeStr) return '';
    try {
        return format(new Date(timeStr), 'MM-dd HH:mm');
    } catch (e) {
        return timeStr;
    }
};

// --- 分页相关 ---
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchTaskList();
};

const handleCurrentChange = (val) => {
  pagination.page = val;
  fetchTaskList();
};

// --- 新增/编辑任务弹窗相关 ---
const dialogVisible = ref(false);
const isEdit = ref(false);
const taskFormRef = ref(null);
const formSubmitting = ref(false);
const taskForm = reactive({
  taskId: null,
  taskName: '',
  taskType: '预防性维护',
  deviceId: null,
  deviceName: '', // 仅前端展示
  description: '',
  planStartTime: '',
  planEndTime: '',
  priority: '中',
  status: '待执行',
  assigneeId: null,
  assigneeName: '',
  reporter: currentUser.name, // 默认当前用户为报告人
  actualStartTime: '',
  actualEndTime: '',
  maintenanceMeasures: '',
  maintenanceResult: '',
  attachmentUrl: '',
  adminRemark: '',
});

// 文件上传相关
const fileList = ref([]); // Element Plus Upload 组件的文件列表

const handleFileChange = (file, uploadedFiles) => {
    if (uploadedFiles.length > 1) {
        uploadedFiles.splice(0, uploadedFiles.length - 1);
        fileList.value = [file];
    } else {
        fileList.value = uploadedFiles;
    }
};

const handleFileRemove = () => {
    taskForm.attachmentUrl = ''; // 清除附件URL
    fileList.value = []; // 清空文件列表
};

const uploadFile = async (options) => {
    try {
        const formData = new FormData();
        formData.append('file', options.file);
        const res = await uploadAttachment(formData);
        if (res.code === 200) {
            taskForm.attachmentUrl = res.data.url;
            ElMessage.success('附件上传成功');
        } else {
            ElMessage.error(res.message || '附件上传失败');
        }
    } catch (error) {
        ElMessage.error('上传附件异常');
        console.error(error);
    }
};


// 表单校验规则
const taskFormRules = {
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  deviceId: [{ required: true, message: '请选择关联设备', trigger: 'change' }],
  taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  description: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
  planStartTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  planEndTime: [
    { required: true, message: '请选择计划完成时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && taskForm.planStartTime && new Date(value) < new Date(taskForm.planStartTime)) {
          callback(new Error('计划完成时间不能早于计划开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  reporter: [{ required: true, message: '请输入报告人', trigger: 'blur' }],
  assigneeId: [
    { validator: (rule, value, callback) => {
        if (isEdit.value && (taskForm.status !== '待执行') && !value) {
            callback(new Error('请选择任务处理人'));
        } else {
            callback();
        }
    }, trigger: 'change'}
  ],
  maintenanceMeasures: [
    { validator: (rule, value, callback) => {
        if (taskForm.status === '已完成' || taskForm.status === '已关闭') {
            if (!value) {
                callback(new Error('已完成/已关闭任务必须填写维修措施'));
            } else {
                callback();
            }
        } else {
            callback();
        }
    }, trigger: 'blur'}
  ],
  maintenanceResult: [
    { validator: (rule, value, callback) => {
        if (taskForm.status === '已完成' || taskForm.status === '已关闭') {
            if (!value) {
                callback(new Error('已完成/已关闭任务必须填写维修结果'));
            } else {
                callback();
            }
        } else {
            callback();
        }
    }, trigger: 'blur'}
  ],
  actualStartTime: [
    { validator: (rule, value, callback) => {
        if (taskForm.status === '执行中' || taskForm.status === '已完成' || taskForm.status === '已关闭') {
            if (!value) {
                callback(new Error('任务开始执行后，实际开始时间不能为空'));
            } else {
                callback();
            }
        } else {
            callback();
        }
    }, trigger: 'change'}
  ],
  actualEndTime: [
    { validator: (rule, value, callback) => {
        if (taskForm.status === '已完成' || taskForm.status === '已关闭') {
            if (!value) {
                callback(new Error('已完成/已关闭任务必须填写实际完成时间'));
            } else if (value && taskForm.actualStartTime && new Date(value) < new Date(taskForm.actualStartTime)) {
                callback(new Error('实际完成时间不能早于实际开始时间'));
            } else {
                callback();
            }
        } else {
            callback();
        }
    }, trigger: 'change'}
  ],
};


// 监听任务状态变化来自动填充时间
watch(() => taskForm.status, (newStatus) => {
    if (isEdit.value) {
        if (newStatus === '执行中' && !taskForm.actualStartTime) {
            taskForm.actualStartTime = new Date().toLocaleString('sv').replace(' ', 'T');
        } else if ((newStatus === '已完成' || newStatus === '已关闭') && !taskForm.actualEndTime) {
            taskForm.actualEndTime = new Date().toLocaleString('sv').replace(' ', 'T');
            if (!taskForm.actualStartTime) { // 如果没开始时间，则等于完成时间
                taskForm.actualStartTime = taskForm.actualEndTime;
            }
        }
        if (newStatus === '待执行' || newStatus === '已驳回') {
            taskForm.actualStartTime = '';
            taskForm.actualEndTime = '';
            taskForm.maintenanceMeasures = '';
            taskForm.maintenanceResult = '';
            taskForm.attachmentUrl = '';
            fileList.value = [];
        }
    }
}, { deep: true });

const handleAddTask = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEditTask = (row) => {
  isEdit.value = true;
  Object.assign(taskForm, row);
  if (taskForm.attachmentUrl) {
    fileList.value = [{ name: taskForm.attachmentUrl.split('/').pop(), url: taskForm.attachmentUrl }];
  } else {
    fileList.value = [];
  }
  dialogVisible.value = true;
};

const handleSubmitForm = async () => {
  if (!taskFormRef.value) return;
  const valid = await taskFormRef.value.validate();
  if (!valid) {
    ElMessage.warning('请检查表单填写是否完整正确');
    return;
  }

  formSubmitting.value = true;
  try {
    let res;
    const dataToSend = { ...taskForm };
    delete dataToSend.deviceName; // 移除前端展示字段

    if (isEdit.value) {
      if (!dataToSend.taskId) throw new Error('编辑ID不存在');
      res = await updateTask(dataToSend);
    } else {
      res = await addTask(dataToSend);
    }

    if (res.code === 200) {
      ElMessage.success(`${isEdit.value ? '保存' : '新增'}任务成功`);
      dialogVisible.value = false;
      fetchTaskList(); // 刷新列表
    } else {
      ElMessage.error(res.message || `${isEdit.value ? '保存' : '新增'}任务失败`);
    }
  } catch (error) {
    ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
    console.error(error);
  } finally {
    formSubmitting.value = false;
  }
};

const handleCloseDialog = () => {
  dialogVisible.value = false;
  resetForm();
  taskFormRef.value?.resetFields();
  fileList.value = []; // 清空文件列表
};

const resetForm = () => {
  taskForm.taskId = null;
  taskForm.taskName = '';
  taskForm.taskType = '预防性维护';
  taskForm.deviceId = null;
  taskForm.deviceName = '';
  taskForm.description = '';
  taskForm.planStartTime = '';
  taskForm.planEndTime = '';
  taskForm.priority = '中';
  taskForm.status = '待执行';
  taskForm.assigneeId = null;
  taskForm.assigneeName = '';
  taskForm.reporter = currentUser.name;
  taskForm.actualStartTime = '';
  taskForm.actualEndTime = '';
  taskForm.maintenanceMeasures = '';
  taskForm.maintenanceResult = '';
  taskForm.attachmentUrl = '';
  taskForm.adminRemark = '';
};

const performAction = async (actionType) => {
    let newStatus = taskForm.status;
    let message = '';
    let successMsg = '';

    switch (actionType) {
        case 'startTask':
            newStatus = '执行中';
            message = '确定要将此任务标记为“执行中”并开始处理吗？';
            successMsg = '任务已进入执行中状态';
            if (!taskForm.actualStartTime) { // 第一次点击开始执行，自动填充开始时间
                taskForm.actualStartTime = new Date().toLocaleString('sv').replace(' ', 'T');
            }
            break;
        case 'submitReport':
            newStatus = '已完成';
            message = '确定要提交维护报告并标记任务为“已完成”吗？';
            successMsg = '维护报告已提交，任务已完成';
            if (!taskForm.actualEndTime) { // 提交报告时，自动填充完成时间
                taskForm.actualEndTime = new Date().toLocaleString('sv').replace(' ', 'T');
            }
            break;
        case 'closeTask': // 管理员操作
            newStatus = '已关闭';
            message = '确定要审核通过并关闭此任务吗？一旦关闭不可更改。';
            successMsg = '任务已关闭';
            if (!taskForm.actualEndTime) { // 管理员强制关闭时，若无完成时间，则填充当前时间
                taskForm.actualEndTime = new Date().toLocaleString('sv').replace(' ', 'T');
            }
            break;
        case 'rejectTask': // 管理员操作
            newStatus = '已驳回';
            message = '确定要驳回此任务吗？请填写管理员备注说明驳回原因。';
            successMsg = '任务已驳回';
            break;
        default:
            return;
    }

    taskForm.status = newStatus; // 临时改变状态以触发校验
    const valid = await taskFormRef.value.validate();
    if (!valid) {
        ElMessage.warning('请检查当前状态下，必填项是否完整！');
        return;
    }

    await ElMessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
    .then(async () => {
        formSubmitting.value = true;
        try {
            const dataToUpdate = { ...taskForm };
            delete dataToUpdate.deviceName;

            const res = await updateTask(dataToUpdate);
            if (res.code === 200) {
                ElMessage.success(successMsg);
                dialogVisible.value = false;
                fetchTaskList();
            } else {
                ElMessage.error(res.message || '操作失败');
            }
        } catch (error) {
            ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
            console.error(error);
        } finally {
            formSubmitting.value = false;
        }
    })
    .catch(() => {
        ElMessage.info('操作已取消');
        // 如果取消，状态改回，并撤销自动填充的时间
        if (actionType === 'startTask') taskForm.actualStartTime = '';
        if (actionType === 'submitReport' || actionType === 'closeTask') taskForm.actualEndTime = '';
    });
};


const handleDeleteTask = async (row) => {
  await ElMessageBox.confirm(`确定要删除任务 "${row.taskName}" (ID: ${row.taskId}) 吗？此操作不可恢复。`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await deleteTask(row.taskId);
        if (res.code === 200) {
          ElMessage.success('删除成功');
          fetchTaskList();
        } else {
          ElMessage.error(res.message || '删除失败');
        }
      } catch (error) {
        ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

const handleBatchDelete = async () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('请选择要删除的任务');
    return;
  }
  const taskNames = selectedTasks.value.map(t => t.taskName).join('，');
  await ElMessageBox.confirm(`确定要删除选中的 ${selectedTasks.value.length} 条维护任务：${taskNames} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const deletePromises = selectedTasks.value.map(t => deleteTask(t.taskId));
        await Promise.all(deletePromises);
        ElMessage.success('批量删除成功');
        fetchTaskList();
        selectedTasks.value = [];
      } catch (error) {
        ElMessage.error(`批量删除失败: ${error.message || '未知错误'}`);
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.info('已取消批量删除');
    });
};

const handleViewDetail = (row) => {
  ElMessageBox.alert(`
    <style>
      .task-detail-content { font-size: 14px; line-height: 1.8; }
      .task-detail-content p { margin-bottom: 8px; }
      .task-detail-content strong { display: inline-block; width: 110px; text-align: right; margin-right: 15px; color: #606266; }
      .task-detail-block { border-top: 1px dashed #eee; padding-top: 15px; margin-top: 15px; }
      .task-detail-block-header { font-weight: bold; font-size: 16px; margin-bottom: 10px; color: #409EFF;}
    </style>
    <div class="task-detail-content">
      <h3>${row.taskName} (任务ID: ${row.taskId})</h3>
      <p><strong>关联设备:</strong> ${row.deviceName} (ID: ${row.deviceId})</p>
      <p><strong>任务类型:</strong> ${row.taskType}</p>
      <p><strong>优先级:</strong> <span style="font-weight: bold; color: ${getTagType(row.priority, 'priority') === 'danger' ? '#F56C6C' : getTagType(row.priority, 'priority') === 'warning' ? '#E6A23C' : '#909399'}">${row.priority}</span></p>
      <p><strong>任务状态:</strong> <span style="font-weight: bold; color: ${getTagType(row.status, 'status') === 'danger' ? '#F56C6C' : getTagType(row.status, 'status') === 'warning' ? '#E6A23C' : getTagType(row.status, 'status') === 'success' ? '#67C23A' : '#909399'}">${row.status}</span></p>
      <p><strong>任务描述:</strong> ${row.description}</p>
      <p><strong>报告人:</strong> ${row.reporter}</p>

      <div class="task-detail-block">
        <div class="task-detail-block-header">计划信息</div>
        <p><strong>计划开始:</strong> ${formatTime(row.planStartTime)}</p>
        <p><strong>计划完成:</strong> ${formatTime(row.planEndTime)}</p>
      </div>

      <div class="task-detail-block">
        <div class="task-detail-block-header">执行信息</div>
        <p><strong>处理人:</strong> ${row.assigneeName || '未分配'}</p>
        <p><strong>实际开始:</strong> ${row.actualStartTime ? formatTime(row.actualStartTime) : '未开始'}</p>
        <p><strong>实际完成:</strong> ${row.actualEndTime ? formatTime(row.actualEndTime) : '未完成'}</p>
        <p><strong>维修措施:</strong> ${row.maintenanceMeasures || '无'}</p>
        <p><strong>维修结果:</strong> ${row.maintenanceResult || '无'}</p>
        <p>
            <strong>附件:</strong>
            ${row.attachmentUrl
                ? `<el-link href="${row.attachmentUrl}" target="_blank">${row.attachmentUrl.split('/').pop()}</el-link>`
                : '无'
            }
        </p>
      </div>

      <div class="task-detail-block">
        <div class="task-detail-block-header">备注</div>
        <p><strong>管理员备注:</strong> ${row.adminRemark || '无'}</p>
      </div>
    </div>
  `, `维护任务 "${row.taskId}" 详情`, {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭',
    customClass: 'task-detail-messagebox',
  });
};

const handleTaskStatusUpdate = async ({ taskId, newStatus }) => {
    loading.value = true;
    try {
        const taskToUpdate = taskList.value.find(t => t.taskId === taskId);
        if (!taskToUpdate) {
            ElMessage.error('找不到任务');
            return;
        }

        if (taskToUpdate.status === '已完成' || taskToUpdate.status === '已关闭') {
            ElMessage.warning(`任务 #${taskId} 已完成或已关闭，不允许再进行操作。`);
            await fetchTaskList(); // 刷新数据，将任务重置回原状态
            return;
        }

        if ((newStatus === '执行中' || newStatus === '已完成' || newStatus === '已关闭') && !taskToUpdate.assigneeId) {
             ElMessage.warning(`任务 #${taskId} 状态变为 "${newStatus}" 要求已分配处理人。`);
             await fetchTaskList(); // 刷新数据，将任务重置回原状态
             return;
        }

        // 如果从待执行拖到执行中
        if (taskToUpdate.status === '待执行' && newStatus === '执行中') {
             ElMessageBox.confirm(`将任务 "${taskToUpdate.taskName}" 状态更改为“执行中”吗？`, '提示', {
                 confirmButtonText: '确定',
                 cancelButtonText: '取消',
                 type: 'info',
             }).then(async () => {
                 const res = await updateTask({
                     taskId: taskId,
                     status: newStatus,
                     actualStartTime: new Date().toLocaleString('sv').replace(' ', 'T')
                 });
                 if (res.code === 200) {
                     ElMessage.success(`任务 #${taskId} 已开始执行`);
                     fetchTaskList();
                 } else {
                     ElMessage.error(res.message || '更新任务状态失败');
                     fetchTaskList();
                 }
             }).catch(() => {
                 ElMessage.info('操作已取消');
                 fetchTaskList();
             });
             return;
        }

        // 如果拖拽到"已完成"或"已关闭"，且未填写报告内容，提示用户点击编辑按钮
        if ((taskToUpdate.status === '执行中' && (newStatus === '已完成' || newStatus === '已关闭')) ||
            (taskToUpdate.status === '待执行' && (newStatus === '已完成' || newStatus === '已关闭'))) { // 待执行直接拖到完成的情况

            ElMessageBox.alert(`
                任务状态从 "${taskToUpdate.status}" 变为 "${newStatus}" 需要填写实际完成时间、维修措施、维修结果等报告内容。
                <br><br>
                请点击任务卡片或右下角的“编辑”按钮，在弹窗中进行详细操作并提交。
            `, '提示', {
                confirmButtonText: '确定',
                type: 'info',
                callback: () => {
                    fetchTaskList(); // 刷新数据，将任务重置回原状态
                    // 可选：handleEditTask(taskToUpdate); 直接打开编辑弹窗
                }
            });
            return;
        }


        // 对于其他简单的状态变化（如执行中互相拖拽，或驳回），直接更新即可
        const res = await updateTask({ taskId: taskId, status: newStatus });
        if (res.code === 200) {
            ElMessage.success(`任务 #${taskId} 状态已更新为 ${newStatus}`);
            fetchTaskList();
        } else {
            ElMessage.error(res.message || '更新任务状态失败');
            fetchTaskList();
        }
    } catch (error) {
        ElMessage.error(`更新任务状态异常: ${error.message || '未知错误'}`);
        console.error(error);
        fetchTaskList();
    } finally {
        loading.value = false;
    }
};
</script>

<style scoped>
.maintenance-task-list-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.search-card,
.content-card {
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 18px;
}

.content-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
}

.list-view {
  /* 列表视图特有样式 */
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.kanban-view {
  /* 看板视图特有样式，保持DraggableKanban的样式即可 */
  padding: 10px 0; /* 留出一些内边距 */
}

.el-divider {
    margin: 20px 0;
}

.maintenance-footer-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px; /* 按钮间距 */
    flex-wrap: wrap; /* 按钮过多时换行 */
}

/* 详情弹窗样式 */
.task-detail-messagebox {
  width: 700px;
}
.task-detail-messagebox .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
</style>
